# Schulte-Cloos (2018): Do European Parliament Elections Foster Challenger Parties' Success on the  National Level?

rm(list=ls())
# Change your working directory to the replication archive
# setwd("")

setwd("./EUP")
dir.create("./EUP/figs")

if (!require("pacman")) { install.packages("pacman") }
pacman::p_load(
  ggplot2, mgcv, 
  np,  ## for kernel estimation
  foreach,  # for parallel computing
  doParallel, # for parallel computing
  Lmoments, # for L-kurtosis
  lmtest, # for wald test
  plm, sandwich, pscl, foreign, 
  dplyr, rgl, clusterSEs, R.utils, gridExtra, 
  readstata13, interflex, extrafont, 
  stargazer, xlsx, readxl, rJava)

####  Load customised binning function ################################################
if(!exists("inter", mode="function")) source("./scripts/binning.R")

### Import Mainfile ######
replication.data <- read.csv("./data/replication.csv")
replication.data <- replication.data[,-1]


#### Create Datasets ####


#### RRP Parties 
RRPferel.data <- subset(replication.data, replication.data$RRPDUM1==1)

#### RLE Parties 
RLEferel.data <- subset(replication.data, replication.data$RLEDUM1==1)

#### GRE Parties 
GREferel.data <- subset(replication.data, replication.data$GREDUM1==1)

### Placebo-Test
RRPplac.data <- subset(replication.data, replication.data$RRPDUM_PLAC==1)





Z <- c("PREVGOV", "midtermEP", "dec1", "dec2", "dec3", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist")

#### Figure 2. Binning estimate and marginal effect (Green Parties) ####

binGRE <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                        Z=Z, Xlabel = "Position of National Election in EP Electoral Cycle",
                        data = GREferel.data, cutoffs=(c(0.25,0.5,0.75)), 
                        FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))

GREbin.p <- binGRE$graph
GREbin.p <- GREbin.p + theme(panel.background = element_blank(),
                             panel.grid.major = element_blank(),
                             panel.border = element_rect(colour = "black", fill=NA, size=1))
GREbin.p  <- GREbin.p + ggtitle("Binning Estimates",
                                subtitle="Green Parties") +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))
print(GREbin.p)
ggsave(filename="./figs/GREbin.pdf", plot=GREbin.p, 
       width=5.68, height=3.73, units="in")




margins <- read_xlsx("./tables/margins_long_GRE.xlsx", sheet="Sheet1")  
meGRE.df <- as.data.frame(t(margins))
meGRE.df <- meGRE.df[,-1]
colnames(meGRE.df) <- unlist(meGRE.df[1,])
meGRE.df <- meGRE.df[-1,] # delete first missing row

x.label<-c(paste("Position of National Election in EP Electoral Cycle"))
y.label<-c(paste("Marginal Effect"))

X.lvls<- c(seq(0.0,0.99,0.01))
lb <- as.numeric(as.character(meGRE.df$ll))
ub <- as.numeric(as.character(meGRE.df$ul))
marg <- as.numeric(as.character(meGRE.df$b))
data <- GREferel.data
X <- "cycle"


out<-data.frame(X.lvls, marg, lb, ub)
ylim = c(-0.5,1.3)  
pGRE <- ggplot()
yrange<-c(ylim[2],ylim[1]+(ylim[2]-ylim[1])*1/6)
maxdiff<-(max(yrange)-min(yrange))
pos<-max(yrange)-maxdiff/20

## mark zero
pGRE <- pGRE + geom_hline(yintercept=0,colour="black",size=1) +
  geom_hline(yintercept=0.5,colour="black",alpha=0.1) +
  geom_hline(yintercept=1,colour="black",alpha=0.1)

## histogram plot
hist.out<-hist(data[,X],breaks=80,plot=FALSE)
n.hist<-length(hist.out$mids)
dist<-hist.out$mids[2]-hist.out$mids[1]
hist.max<-max(hist.out$counts)

histX<-data.frame(ymin=rep(min(yrange)-maxdiff/5,n.hist),
                  ymax=hist.out$counts/hist.max*maxdiff/5+min(yrange)-maxdiff/5,
                  xmin=hist.out$mids-dist/2,
                  xmax=hist.out$mids+dist/2)

ylim2 = c(ylim[1]-(ylim[2]-ylim[1])*0.25/6, ylim[2]+(ylim[2]-ylim[1])*0.4/6)
pGRE <- pGRE + geom_rect(data=histX,aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax),
                         colour="gray50",alpha=0,size=0.5) +
  coord_cartesian(xlim = c(0,1), ylim = ylim2)
pGRE<-pGRE + ggtitle("Linear Interaction Effect"
                     , subtitle = "Green Parties") +
  theme(panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.border = element_rect(colour = "black", fill=NA, size=1)) +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +  
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  theme(axis.title.x = element_text(margin = margin(15))) +
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))

## draw plot 
pGRE<-pGRE + geom_line(data=out,aes(X.lvls,marg))    +
  geom_line(data=out, aes(X.lvls, lb), colour="black", linetype=2,alpha=0.4)+
  geom_line(data=out, aes(X.lvls, ub), colour="black", linetype=2,alpha=0.4)+
  xlab(x.label) + ylab(y.label)
ggsave(filename="./figs/GREme.pdf", plot=pGRE, 
       width=5.68, height=3.73, units="in")




#### Figure 3: Binning estimate and marginal effect (Populist Radical Right) ####

binRRP <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                        Z=Z, Xlabel = "Position of National Election in EP Electoral Cycle",
                        data = RRPferel.data, cutoffs=(c(0.25,0.5,0.75)), 
                        FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))

RRPbin.p <- binRRP$graph
RRPbin.p <- RRPbin.p + theme(panel.background = element_blank(),
                             panel.grid.major = element_blank(),
                             panel.border = element_rect(colour = "black", fill=NA, size=1))
RRPbin.p  <- RRPbin.p + ggtitle("Binning Estimates",
                                subtitle = "Populist Radical Right") +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))
print(RRPbin.p)
ggsave(filename="./figs/RRPbin.pdf", plot=RRPbin.p, 
       width=5.68, height=3.73, units="in")


margins <- read_xlsx("./tables/margins_long_RRP.xlsx", sheet="Sheet1")  
meRRP.df <- as.data.frame(t(margins))
meRRP.df <- meRRP.df[,-1]
colnames(meRRP.df) <- unlist(meRRP.df[1,])
meRRP.df <- meRRP.df[-1,] # delete first missing row

x.label<-c(paste("Position of National Election in EP Electoral Cycle"))
y.label<-c(paste("Marginal Effect"))

X.lvls<- c(seq(0.0,0.99,0.01))
lb <- as.numeric(as.character(meRRP.df$ll))
ub <- as.numeric(as.character(meRRP.df$ul))
marg <- as.numeric(as.character(meRRP.df$b))
data <- RRPferel.data
X <- "cycle"


out<-data.frame(X.lvls, marg, lb, ub)
ylim = c(-0.5,1.3)  
pRRP <- ggplot()
yrange<-c(ylim[2],ylim[1]+(ylim[2]-ylim[1])*1/6)
maxdiff<-(max(yrange)-min(yrange))
pos<-max(yrange)-maxdiff/20

## mark zero
pRRP <- pRRP + geom_hline(yintercept=0,colour="black",size=1) +
  geom_hline(yintercept=0.5,colour="black",alpha=0.1) +
  geom_hline(yintercept=1,colour="black",alpha=0.1)

## histogram plot
hist.out<-hist(data[,X],breaks=80,plot=FALSE)
n.hist<-length(hist.out$mids)
dist<-hist.out$mids[2]-hist.out$mids[1]
hist.max<-max(hist.out$counts)

histX<-data.frame(ymin=rep(min(yrange)-maxdiff/5,n.hist),
                  ymax=hist.out$counts/hist.max*maxdiff/5+min(yrange)-maxdiff/5,
                  xmin=hist.out$mids-dist/2,
                  xmax=hist.out$mids+dist/2)

ylim2 = c(ylim[1]-(ylim[2]-ylim[1])*0.25/6, ylim[2]+(ylim[2]-ylim[1])*0.4/6)
pRRP <- pRRP + geom_rect(data=histX,aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax),
                         colour="gray50",alpha=0,size=0.5) +
  coord_cartesian(xlim = c(0,1), ylim = ylim2)
pRRP <-pRRP + ggtitle("Quadratic Interaction Effect"
                     , subtitle = "Populist Radical Right") +
  theme(panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.border = element_rect(colour = "black", fill=NA, size=1)) +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +  
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  theme(axis.title.x = element_text(margin = margin(15))) +
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))


## draw plot 
pRRP <-pRRP + geom_line(data=out,aes(X.lvls,marg))    +
  geom_line(data=out, aes(X.lvls, lb), colour="black", linetype=2,alpha=0.4)+
  geom_line(data=out, aes(X.lvls, ub), colour="black", linetype=2,alpha=0.4)+
  xlab(x.label) + ylab(y.label)
ggsave(filename="./figs/RRPme.pdf", plot=pRRP, 
       width=5.68, height=3.73, units="in")





#### Figure 4: Binning estimate and marginal effect (Populist Radical Left) ####

binRLE <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                        Z=Z, Xlabel = "Position of National Election in EP Electoral Cycle",
                        data = RLEferel.data, cutoffs=(c(0.25,0.5,0.75)), 
                        FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))
RLEbin.p <- binRLE$graph
RLEbin.p <- RLEbin.p + theme(panel.background = element_blank(),
                             panel.grid.major = element_blank(),
                             panel.border = element_rect(colour = "black", fill=NA, size=1))
RLEbin.p  <- RLEbin.p + ggtitle("Binning Estimates",
                                subtitle="Populist Radical Left") +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))
print(RLEbin.p)
ggsave(filename="./figs/RLEbin.pdf", plot=RLEbin.p, 
       width=5.68, height=3.73, units="in")


margins <- read_xlsx("./tables/margins_long_RLE.xlsx", sheet="Sheet1")  

meRLE.df <- as.data.frame(t(margins))
meRLE.df <- meRLE.df[,-1]
colnames(meRLE.df) <- unlist(meRLE.df[1,])
meRLE.df <- meRLE.df[-1,] # delete first missing row

x.label<-c(paste("Position of National Election in EP Electoral Cycle"))
y.label<-c(paste("Marginal Effect"))

X.lvls<- c(seq(0.0,0.99,0.01))
lb <- as.numeric(as.character(meRLE.df$ll))
ub <- as.numeric(as.character(meRLE.df$ul))
marg <- as.numeric(as.character(meRLE.df$b))
data <- RLEferel.data
X <- "cycle"


out<-data.frame(X.lvls, marg, lb, ub)
ylim = c(-0.5,1.3)  
pRLE <- ggplot()
yrange<-c(ylim[2],ylim[1]+(ylim[2]-ylim[1])*1/6) # range of histogram
maxdiff<-(max(yrange)-min(yrange))
pos<-max(yrange)-maxdiff/20

## mark zero
pRLE <- pRLE + geom_hline(yintercept=0,colour="black",size=1) +
  geom_hline(yintercept=0.5,colour="black",alpha=0.1) +
  geom_hline(yintercept=1,colour="black",alpha=0.1)

## histogram plot
hist.out<-hist(data[,X],breaks=80,plot=FALSE)
n.hist<-length(hist.out$mids)
dist<-hist.out$mids[2]-hist.out$mids[1]
hist.max<-max(hist.out$counts)

histX<-data.frame(ymin=rep(min(yrange)-maxdiff/5,n.hist),
                  ymax=hist.out$counts/hist.max*maxdiff/5+min(yrange)-maxdiff/5,
                  xmin=hist.out$mids-dist/2,
                  xmax=hist.out$mids+dist/2)

ylim2 = c(ylim[1]-(ylim[2]-ylim[1])*0.25/6, ylim[2]+(ylim[2]-ylim[1])*0.4/6)
pRLE <- pRLE + geom_rect(data=histX,aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax),
                         colour="gray50",alpha=0,size=0.5) +
  coord_cartesian(xlim = c(0,1), ylim = ylim2)
pRLE<-pRLE + ggtitle("Linear Interaction Effect"
                     , subtitle = "Populist Radical Left") +
  theme(panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.border = element_rect(colour = "black", fill=NA, size=1)) +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  theme(axis.title.x = element_text(margin = margin(15))) +
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))

## draw plot 
pRLE<-pRLE + geom_line(data=out,aes(X.lvls,marg))    +
  geom_line(data=out, aes(X.lvls, lb), colour="black", linetype=2,alpha=0.4)+
  geom_line(data=out, aes(X.lvls, ub), colour="black", linetype=2,alpha=0.4)+
  xlab(x.label) + ylab(y.label)
ggsave(filename="./figs/RLEme.pdf", plot=pRLE, 
       width=5.68, height=3.73, units="in")






#### Table 1: report LIE Wald test results ####

table(binRRP$p.wald)
table(binGRE$p.wald)
table(binRLE$p.wald)







####  Table 1: Pairs Cluster Bootstrapped SE  ####

RRPplm <- plm(formula = 
                VOTE ~ EP_VOTE + cycle + cycle_sq + EP_VOTE*cycle + EP_VOTE*cycle_sq
              + PREVGOV + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
              + EPthres  + lndist + EPlndist , 
              data=RRPferel.data, model="within", index=c("country_id", "election_date"))
summary(RRPplm)


bootsRRP <- cluster.bs.plm(mod=RRPplm, dat=RRPferel.data, cluster="group", ci.level = 0.95, 
                           boot.reps = 1000, cluster.se = TRUE, report = TRUE, 
                           prog.bar = TRUE)
print(bootsRRP)


RLEplm <- plm(formula = 
                    VOTE ~ EP_VOTE + cycle + EP_VOTE*cycle 
                  + PREVGOV + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
                  + EPthres + lndist + EPlndist , 
                  data=RLEferel.data, model="within", index=c("country_id", "election_date"))
summary(RLEplm)
bootsRLE <- cluster.bs.plm(mod=RLEplm, dat=RLEferel.data, cluster="group", ci.level = 0.95, 
                               boot.reps = 1000, cluster.se = TRUE, report = TRUE, 
                               prog.bar = TRUE)
print(bootsRLE)



GREplm <- plm(formula = 
                VOTE ~ EP_VOTE + cycle + EP_VOTE*cycle 
              + PREVGOV + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
              + EPthres + lndist + EPlndist , 
              data=GREferel.data, model="within", index=c("country_id", "election_date"))
summary(GREplm)
bootsGRE <- cluster.bs.plm(mod=GREplm, dat=GREferel.data, cluster="group", ci.level = 0.95, 
                           boot.reps = 1000, cluster.se = TRUE, report = TRUE, 
                           prog.bar = TRUE)
print(bootsGRE)



stargazer(RLEplm, GREplm, RRPplm, type="text", out="./tables/table1.txt",
          column.labels=c("Populist Radical Left", "Green Parties", "Populist Radical Right"), 
          dep.var.labels   = c(""),
          dep.var.caption = c(""),
          title=c("Table 1: Fixed effects regression on national vote share by party families"),
          header=FALSE, 
          digits=2,
          font.size="small") 



#### Table 2: Pairs Cluster Bootstrapped SE #####

GRE_EP <- plm(formula = 
                   DIFFVOTE ~ cycle + PREVGOV +
                   + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement + EPthres
                 + lndist + EPlndist , 
                 data=GREferel.data, model="within", index=c("country_id", "election_date"))
summary(GRE_EP)
bootsGRE_EP <- cluster.bs.plm(mod=GRE_EP, dat=GREferel.data, cluster="group", ci.level = 0.95, 
                                 boot.reps = 1000, cluster.se = TRUE, report = TRUE, 
                                 prog.bar = TRUE)
print(bootsGRE_EP)


RLE_EP <- plm(formula = 
                   DIFFVOTE ~ cycle + PREVGOV
                 + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement + EPthres
                 + lndist + EPlndist , 
                 data=RLEferel.data, model="within", index=c("country_id", "election_date"))
summary(RLE_EP)
bootsRLE_EP <- cluster.bs.plm(mod=RLE_EP, dat=RLEferel.data, cluster="group", ci.level = 0.95, 
                                 boot.reps = 1000, cluster.se = TRUE, report = TRUE, 
                                 prog.bar = TRUE)
print(bootsRLE_EP)



RRP_EP <-  plm(formula = 
                    DIFFVOTE ~ cycle_sq + cycle +
                    + PREVGOV + midtermEP + dec1 + dec2 + dec3 + unemployment + EPinvolvement + EPthres
                  + lndist + EPlndist , 
                  data=RRPferel.data, model="within", index=c("country_id", "election_date"))
summary(RRP_EP)
bootsRRP_EP <- cluster.bs.plm(mod=RRP_EP, dat=RRPferel.data, cluster="group", ci.level = 0.95, 
                                 boot.reps = 1000, cluster.se = TRUE, report = TRUE, 
                                 prog.bar = TRUE)
print(bootsRRP_EP)



stargazer(RLE_EP, GRE_EP, RRP_EP, type="text", out="./tables/table2.txt",
          column.labels=c("Populist Radical Left", "Green Parties", "Populist Radical Right"), 
          dep.var.labels   = c(""),
          dep.var.caption = c(""),
          title=c("Table 2: Fixed effects regression on national vote share by party families"),
          header=FALSE, 
          digits=2,
          font.size="small") 





#### Online appendix ####




#### Figure B.1 Semi-parametric marginal effect estimate (Populist Radical Left) ####

Z <- c("PREVGOV", "midtermEP", "dec1", "dec2", "dec3", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist")
kernelRLE <- inter.kernel(Y = "VOTE", D = "EP_VOTE", X = "cycle",
                          Z=Z, Xlabel= "Position of National Election in EP Electoral Cycle",
                          data = RLEferel.data,
                          ylim=c(-0.5,1.3), xlim=c(0,1))
RLEkernel.p <- kernelRLE$graph
RLEkernel.p <- RLEkernel.p + theme(panel.background = element_blank(),
                                   panel.grid.major = element_blank(),
                                   panel.border = element_rect(colour = "black", fill=NA, size=1))
RLEkernel.p  <- RLEkernel.p + ggtitle("Semi Parametric Kernel Smoothed Varying Coefficient Model",
                                      subtitle="Populist Radical Left") +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))

print(RLEkernel.p)
ggsave(filename="./figs/RLEkernel.pdf", plot=RLEkernel.p, 
       width=7.1, height=4.6625, units="in")



#### Figure B.2 Semi-parametric marginal effect estimate (Green Parties) ####

Z <- c("PREVGOV", "midtermEP", "dec1", "dec2", "dec3", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist")
kernelGRE <- inter.kernel(Y = "VOTE", D = "EP_VOTE", X = "cycle",
                          Z=Z, Xlabel= "Position of National Election in EP Electoral Cycle",
                          data = GREferel.data,
                          ylim=c(-0.5,1.3), xlim=c(0,1))
GREkernel.p <- kernelGRE$graph
GREkernel.p <- GREkernel.p + theme(panel.background = element_blank(),
                                   panel.grid.major = element_blank(),
                                   panel.border = element_rect(colour = "black", fill=NA, size=1))
GREkernel.p  <- GREkernel.p + ggtitle("Semi Parametric Kernel Smoothed Varying Coefficient Model",
                                      subtitle="Green Parties") +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))

print(GREkernel.p)
ggsave(filename="./figs/GREkernel.pdf", plot=GREkernel.p, 
       width=7.1, height=4.6625, units="in")





#### Figure B.3 Semi-parametric marginal effect estimate (Populist Radical Right) ####

Z <- c("PREVGOV", "midtermEP", "dec1", "dec2", "dec3", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist")
kernelRRP <- inter.kernel(Y = "VOTE", D = "EP_VOTE", X = "cycle",
                          Z=Z, Xlabel= "Position of National Election in EP Electoral Cycle",
                          data = RRPferel.data,  conf.level = 0.95, 
                          ylim=c(-0.5,1.3), xlim=c(0,1))


RRPkernel.p <- kernelRRP$graph
RRPkernel.p <- RRPkernel.p + theme(panel.background = element_blank(),
                                   panel.grid.major = element_blank(),
                                   panel.border = element_rect(colour = "black", fill=NA, size=1))
RRPkernel.p  <- RRPkernel.p + ggtitle("Semi Parametric Kernel Smoothed Varying Coefficient Model",
                                      subtitle = "Populist Radical Right") +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))

print(RRPkernel.p)
ggsave(filename="./figs/RRPkernel.pdf", plot=RRPkernel.p, 
       width=7.1, height=4.6625, units="in")














#### Figure B.4. Placebo Test: Binning Estimate and Kernel ####

Zplac <- c("dec1" , "dec2" , "dec3" , "GOV", "unemployment", "EPinvolvement", "EPthres" , "EPlndist", "lndist", "midtermEP")


binRRPplac <- inter.binning(Y = "EP_VOTE", D = "NE_VOTE", X = "SOcycle", 
                            Z=Zplac, Xlabel="Position of EP Election in National Electoral Cycle",
                            data = RRPplac.data, na.rm=TRUE,
                            cutoffs=(c(0.25,0.5,0.75)), 
                            FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))
RRPbinplac.p <- binRRPplac$graph
RRPbinplac.p <- RRPbinplac.p + theme(panel.background = element_blank(),
                                     panel.grid.major = element_blank(),
                                     panel.border = element_rect(colour = "black", fill=NA, size=1))
RRPbinplac.p  <- RRPbinplac.p + ggtitle("Binning Estimates",
                                        subtitle = "Placebo - Populist Radical Right") +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))
print(RRPbinplac.p)
ggsave(filename="./figs/RRPbinplac.pdf", plot=RRPbinplac.p, 
       width=5.68, height=3.73, units="in")




margins <- read_xlsx("./tables/margins_long_RRP_plac.xlsx", sheet="Sheet1")  
meRRPplac.df <- as.data.frame(t(margins))
meRRPplac.df <- meRRPplac.df[,-1]
colnames(meRRPplac.df) <- unlist(meRRPplac.df[1,])
meRRPplac.df <- meRRPplac.df[-1,] # delete first missing row

x.label<-c(paste("Position of EP Election in National Electoral Cycle"))
y.label<-c(paste("Marginal Effect"))

X.lvls<- c(seq(0.0,0.99,0.01))
lb <- as.numeric(as.character(meRRPplac.df$ll))
ub <- as.numeric(as.character(meRRPplac.df$ul))
marg <- as.numeric(as.character(meRRPplac.df$b))
data <- RRPplac.data
X <- "SOcycle"


out<-data.frame(X.lvls, marg, lb, ub)
ylim = c(-0.5,1.3)  
pRRPplac <- ggplot()
yrange<-c(ylim[2],ylim[1]+(ylim[2]-ylim[1])*1/6)
maxdiff<-(max(yrange)-min(yrange))
pos<-max(yrange)-maxdiff/20

## mark zero
pRRPplac <- pRRPplac + geom_hline(yintercept=0,colour="black",size=1) +
  geom_hline(yintercept=0.5,colour="black",alpha=0.1) +
  geom_hline(yintercept=1,colour="black",alpha=0.1)

## histogram plot
hist.out<-hist(data[,X],breaks=80,plot=FALSE)
n.hist<-length(hist.out$mids)
dist<-hist.out$mids[2]-hist.out$mids[1]
hist.max<-max(hist.out$counts)

histX<-data.frame(ymin=rep(min(yrange)-maxdiff/5,n.hist),
                  ymax=hist.out$counts/hist.max*maxdiff/5+min(yrange)-maxdiff/5,
                  xmin=hist.out$mids-dist/2,
                  xmax=hist.out$mids+dist/2)

ylim2 = c(ylim[1]-(ylim[2]-ylim[1])*0.25/6, ylim[2]+(ylim[2]-ylim[1])*0.4/6)
pRRPplac <- pRRPplac + geom_rect(data=histX,aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax),
                                 colour="gray50",alpha=0,size=0.5) +
  coord_cartesian(xlim = c(0,1), ylim = ylim2)
pRRPplac<-pRRPplac + ggtitle("Linear Interaction Effect"
                             , subtitle = "Placebo - Populist Radical Right") +
  theme(panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.border = element_rect(colour = "black", fill=NA, size=1)) +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  theme(axis.title.x = element_text(margin = margin(15))) +
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))

## draw plot 

pRRPplac<-pRRPplac + geom_line(data=out,aes(X.lvls,marg))    +
  geom_line(data=out, aes(X.lvls, lb), colour="black", linetype=2,alpha=0.4)+
  geom_line(data=out, aes(X.lvls, ub), colour="black", linetype=2,alpha=0.4)+
  xlab(x.label) + ylab(y.label)
ggsave(filename="./figs/RRPplacme.pdf", plot=pRRPplac, 
       width=5.68, height=3.73, units="in")




# kernel-smoothed varying coefficient model
kernelRRPplac <- inter.kernel(Y = "EP_VOTE", D = "NE_VOTE", X="SOcycle", 
                              Z=Zplac, Xlabel = "Position of EP Election in National Electoral Cycle",
                              data = RRPplac.data, na.rm=TRUE,
                              ylim = c(-0.5,1.3), xlim=c(0,1))

RRPkernelplac.p <- kernelRRPplac$graph
RRPkernelplac.p <- RRPkernelplac.p + theme(panel.background = element_blank(),
                                           panel.grid.major = element_blank(),
                                           panel.border = element_rect(colour = "black", fill=NA, size=1))
RRPkernelplac.p  <- RRPkernelplac.p + ggtitle("Semi Parametric Kernel Smoothed Varying Coefficient Model",
                                              subtitle="Placebo - Populist Radical Right") +
  theme(axis.text = element_text(size = 15),
        axis.title = element_text(size = 15),
        text = element_text(size = 15)) +
  theme(plot.title = element_text(hjust= 0.5)) +
  theme(plot.subtitle = element_text(hjust= 0.5)) +
  theme(plot.margin=unit(c(0.2,0.5,0.2,0.2),"cm"))+
  scale_y_continuous(expand = c(0,0)) + scale_x_continuous(expand = c(0,0))

print(RRPkernelplac.p)
ggsave(filename="./figs/RRPkernelplac.pdf", plot=RRPkernelplac.p, 
       width=7.1, height=4.6625, units="in")





#### Table B.4 Placebo-Test Populist Right Support ####

RRPplac.data <- as.data.frame(RRPplac.data)

RRPplacplm <- plm(formula = 
                    EP_VOTE ~ NE_VOTE + SOcycle + NE_VOTE*SOcycle 
                  + GOV + dec1 + dec2 + dec3 + unemployment + EPinvolvement + midtermEP +
                  + EPthres  + lndist + EPlndist , 
                  data=RRPplac.data, model="within", index=c("country_id", "election_date"))
summary(RRPplacplm)


bootsRRPplac <- cluster.bs.plm(mod=RRPplacplm, dat=RRPplac.data, cluster="group", ci.level = 0.95, 
                               boot.reps = 1000, cluster.se = TRUE, report = TRUE, 
                               prog.bar = TRUE)
print(bootsRRPplac)


table(binRRPplac$p.wald) #0.428 


stargazer(RRPplacplm, type="text", out="./tables/tableB4.txt",
          column.labels = c("Placebo: Populist Radical Right"),
          dep.var.labels = c(""), 
          dep.var.caption = c(""), 
          digits=2,
          title=c("Table B.4: Fixed effects regression on EP populist radical right vote share"))




#### Table B.5: Populist Right Correlates and Inclusion of Contested Parties ####



#### RRP Success Correlates  

RRPcorrplm <- plm(formula = 
                VOTE ~ EP_VOTE + cycle + cycle_sq + EP_VOTE*cycle + EP_VOTE*cycle_sq
              + PREVGOV + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
              + EPthres  + lndist + EPlndist + tasyl + turnout + cmp_competitor2 , 
              data=RRPferel.data, model="within", index=c("country_id", "election_date"))
summary(RRPcorrplm)



Z <- c("midtermEP", "dec1", "dec2", "dec3", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist",
       "tasyl", "turnout", "cmp_competitor2")

binRRPcorr <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                           Z=Z, Xlabel = "Position of National Election in EP Electoral Cycle",
                           data = RRPferel.data, cutoffs=(c(0.25,0.5,0.75)), 
                           FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))

binRRPcorr$graph


## RRP inclusion of contested populist right parties 
RRPextferel.data <- subset(replication.data, replication.data$RRPDUM_ext==1)

RRPextplm <- plm(formula = 
                   VOTE ~ EP_VOTE + cycle + cycle_sq + EP_VOTE*cycle + EP_VOTE*cycle_sq
                 + PREVGOV + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
                 + EPthres  + lndist + EPlndist , 
                 data=RRPextferel.data, model="within", index=c("country_id", "election_date"))
summary(RRPextplm) 


Z <- c("midtermEP", "dec1", "dec2", "dec3", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist")

binRRPext <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                           Z=Z, Xlabel = "Position of National Election in EP Electoral Cycle",
                           data = RRPextferel.data, cutoffs=(c(0.25,0.5,0.75)), 
                           FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))


stargazer(RRPcorrplm, RRPextplm, type="text", out="./tables/tableB5.txt", 
          column.labels = c("Inclusion of Populist Radical Right Correlates", 
                            "Inclusion of Contested Populist Radical Right Parties"),
          dep.var.labels = c(""), 
          dep.var.caption = c(""), 
          digits=2,
          title=c("Table B.5: Fixed effects regression on national vote share by party families"))



#### Table B.6.: Excluding Government Parties, Concurrent Elections and Party Fixed Effects ####
RLEexclcon.data <- subset(RLEferel.data, RLEferel.data$cycle!=0)
GREexclcon.data <- subset(GREferel.data, GREferel.data$cycle!=0)
RRPexclcon.data <- subset(RRPferel.data, RRPferel.data$cycle!=0)

Z <- c("PREVGOV", "midtermEP", "dec1", "dec2", "dec3", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist")

## Exclusion of Concurrent Elections - LIE p-values ##
#RLE
RLEexclconplm <- plm(formula = 
                       VOTE ~ EP_VOTE + cycle + EP_VOTE*cycle +
                      PREVGOV + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
                     + EPthres  + lndist + EPlndist , 
                     data=RLEexclcon.data, model="within", index=c("country_id", "election_date"))
summary(RLEexclconplm)

binRLEexclcon <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                               Z=Z, Xlabel = "Position of National Election in EP Electoral Cycle",
                               data = RLEexclcon.data, cutoffs=(c(0.25,0.5,0.75)), 
                               FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))
binRLEexclcon$graph


#GRE
GREexclconplm <- plm(formula = 
                       VOTE ~ EP_VOTE + cycle + EP_VOTE*cycle +
                     + PREVGOV + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
                     + EPthres  + lndist + EPlndist , 
                     data=GREexclcon.data, model="within", index=c("country_id", "election_date"))
summary(GREexclconplm)

binGREexclcon <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                               Z=Z, Xlabel = "Position of National Election in EP Electoral Cycle",
                               data = GREexclcon.data, cutoffs=(c(0.25,0.5,0.75)), 
                               FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))
binGREexclcon$graph


# RRP 
RRPexclconplm <- plm(formula = 
                       VOTE ~ EP_VOTE + cycle + cycle_sq + EP_VOTE*cycle + EP_VOTE*cycle_sq
                     + PREVGOV + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
                     + EPthres  + lndist + EPlndist , 
                     data=RRPexclcon.data, model="within", index=c("country_id", "election_date"))
summary(RRPexclconplm) 


binRRPexclcon <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                               Z=Z, Xlabel = "Position of National Election in EP Electoral Cycle",
                               data = RRPexclcon.data, cutoffs=(c(0.25,0.5,0.75)), 
                               FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))
binRRPexclcon$graph


table(binRLEexclcon$p.wald) #0.862
table(binGREexclcon$p.wald) #0.754
table(binRRPexclcon$p.wald) #0.001


## Excluding Government Actors - LIE p-values ##
GREexclgov.data <- subset(replication.data, replication.data$GREexcl==1 )
RLEexclgov.data <- subset(replication.data, replication.data$RLEexcl==1 )
RRPexclgov.data <- subset(replication.data, replication.data$RRPexcl==1 )

Zexclgov <- c("midtermEP", "dec1", "dec2", "dec3", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist")


#RLE
RLEexclgovplm <- plm(formula = 
                       VOTE ~ EP_VOTE + cycle + EP_VOTE*cycle 
                     + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
                     + EPthres  + lndist + EPlndist , 
                     data=RLEexclgov.data, model="within", index=c("country_id", "election_date"))
summary(RLEexclgovplm)
binRLEexclgov <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                               Z=Zexclgov, Xlabel = "Position of National Election in EP Electoral Cycle",
                               data = RLEexclgov.data, cutoffs=(c(0.25,0.5,0.75)), 
                               FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))
binRLEexclgov$graph

#GRE
GREexclgovplm <- plm(formula = 
                       VOTE ~ EP_VOTE + cycle + EP_VOTE*cycle +
                     + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
                     + EPthres  + lndist + EPlndist , 
                     data=GREexclgov.data, model="within", index=c("country_id", "election_date"))
summary(GREexclgovplm)

binGREexclgov <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                               Z=Zexclgov, Xlabel = "Position of National Election in EP Electoral Cycle",
                               data = GREexclgov.data, cutoffs=(c(0.25,0.5,0.75)), 
                               FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))
binGREexclgov$graph


#RRP
RRPexclgovplm <- plm(formula = 
                       VOTE ~ EP_VOTE + cycle + cycle_sq + EP_VOTE*cycle + EP_VOTE*cycle_sq
                     + dec1 + dec2 + dec3 + midtermEP + unemployment + EPinvolvement 
                     + EPthres  + lndist + EPlndist , 
                     data=RRPexclgov.data, model="within", index=c("country_id", "election_date"))
summary(RRPexclgovplm)
binRRPexclgov <- inter.binning(Y = "VOTE", D = "EP_VOTE", X = "cycle", 
                               Z=Zexclgov, Xlabel = "Position of National Election in EP Electoral Cycle",
                               data = RRPexclgov.data, cutoffs=(c(0.25,0.5,0.75)), 
                               FE="country_id", ylim=c(-0.5,1.3), xlim=c(0,1))
binRRPexclgov$graph



table(binRLEexclgov$p.wald) #0.898
table(binGREexclgov$p.wald) #0.052
table(binRRPexclgov$p.wald) #0.001




## Party-Fixed Effects - LIE p-values  ##
partyfixed.data <- read.csv("./data/replication_parfe.csv")
partyfixed.data <- partyfixed.data[,-1]


partyRLE.data <- subset(partyfixed.data, partyfixed.data$RLE_DUM==1)
ZpartyRLE <- c("prevgov_RLE", "midtermEP", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist", "dec1", "dec2", "dec3")
partyGRE.data <- subset(partyfixed.data, partyfixed.data$GRE_DUM==1)
ZpartyGRE <- c("prevgov_Gre", "midtermEP", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist", "dec1", "dec2", "dec3")
partyRRP.data <- subset(partyfixed.data, partyfixed.data$RRP_DUM==1)
ZpartyRRP <- c("prevgov_RRP", "midtermEP", "unemployment", "EPinvolvement", "EPthres", "lndist", "EPlndist", "dec1", "dec2", "dec3")


RLEpartyfe <-  plm(formula = 
                     vote_RLE ~ EPvote_RLE + cycle + EPvote_RLE*cycle + prevgov_RLE +
                     midtermEP + dec1 + dec2 + dec3 + unemployment + EPinvolvement +
                     EPthres + lndist + EPlndist, 
                   data=partyRLE.data, model="within", index=c("partylevel_id", "election_date")) 
summary(RLEpartyfe)
binpartyRLE <- inter.binning(Y = "vote_RLE", D = "EPvote_RLE", X = "cycle", 
                             Z=ZpartyRLE, Xlabel = "Position of National Election in EP Electoral Cycle",
                             data = partyRLE.data, cutoffs=(c(0.25,0.5,0.75)), 
                             FE="partylevel_id", ylim=c(-0.5,1.3), xlim=c(0,1))
binpartyRLE$graph


GREpartyfe <-  plm(formula = 
                     vote_Gre ~ EPvote_Gre + cycle + EPvote_Gre*cycle + prevgov_Gre +
                     midtermEP + dec1 + dec2 + dec3 + unemployment + EPinvolvement +
                     EPthres + lndist + EPlndist, 
                   data=partyGRE.data, model="within", index=c("partylevel_id", "election_date")) 
summary(GREpartyfe)
binpartyGRE <- inter.binning(Y = "vote_Gre", D = "EPvote_Gre", X = "cycle", 
                             Z=ZpartyGRE, Xlabel = "Position of National Election in EP Electoral Cycle",
                             data = partyGRE.data, cutoffs=(c(0.25,0.5,0.75)), 
                             FE="partylevel_id", ylim=c(-0.5,1.3), xlim=c(0,1))
binpartyGRE$graph


RRPpartyfe <-  plm(formula = 
                     vote_RRP ~ EPvote_RRP + cycle + cycle_sq + EPvote_RRP*cycle + EPvote_RRP*cycle_sq + prevgov_RRP +
                     midtermEP + dec1 + dec2 + dec3 + unemployment + EPinvolvement +
                     EPthres + lndist + EPlndist, 
                   data=partyRRP.data, model="within", index=c("partylevel_id", "election_date")) 
summary(RRPpartyfe)
binpartyRRP <- inter.binning(Y = "vote_RRP", D = "EPvote_RRP", X = "cycle", 
                             Z=ZpartyRRP, Xlabel = "Position of National Election in EP Electoral Cycle",
                             data = partyRRP.data, cutoffs=(c(0.25,0.5,0.75)), 
                             FE="partylevel_id", ylim=c(-0.5,1.3), xlim=c(0,1))
binpartyRRP$graph


table(binpartyRLE$p.wald) #0.7078
table(binpartyGRE$p.wald) #0.146
table(binpartyRRP$p.wald) #0.001


stargazer(RLEexclconplm, GREexclconplm, RRPexclconplm, 
          RLEexclgovplm, GREexclgovplm, RRPexclgovplm, 
          RLEpartyfe, GREpartyfe, RRPpartyfe, type="text", out="./tables/tableB6.txt", 
          column.labels = c("Populist Radical Left", "Green Parties", "Populist Radical Right", 
                            "Populist Radical Left", "Green Parties", "Populist Radical Right",
                            "Populist Radical Left", "Green Parties", "Populist Radical Right"), 
          dep.var.labels = c("Excluding Concurrent Elections (1-3), Excluding Government Parties (4-6), Party Fixed Effects (7-9)"), 
          dep.var.caption = c(""), 
          digits=2,
          title=c("Table B.6: Fixed effects regression on national vote share by party families"))


